package gui.actions;

import gui.models.ImportModel;

import javax.swing.JComponent;
import javax.swing.JOptionPane;

import common.Fictionator;
import common.interfaces.ConfigurationsInterface;

public class ImportAction extends WorkerAction {

    private static final long serialVersionUID = 1L;

    private ImportModel model;
    private ConfigurationsInterface configurationsLogic;
    private boolean actionResult;
    
    public ImportAction(JComponent owner, ImportModel model) {
        super(owner);
        this.model = model;
        configurationsLogic = Fictionator.getInstance().getConfigurationsLogic();
    }
    
    @Override
    public boolean isAllowToRunOperation() {
        return true;
    }
    
    @Override
    public void runOperation() throws Exception {
        int guiSessionID = Fictionator.getInstance().getGuiSessionID();
        actionResult = configurationsLogic.importToDB(
                guiSessionID, model.isOnlineImport(), model.getSelectedFile());
    }
    
    @Override
    public void operationSucceed() {
        model.setSuccesfulImport(actionResult);
        model.notifyObservers();
        if (!actionResult) {
            String errorMsg = "There are currently other users connected to the system, so import could " +
                "not be performed";
            String errorTitle = "Database import didn't complete";
            JOptionPane.showMessageDialog(getOwner(), errorMsg, errorTitle, JOptionPane.ERROR_MESSAGE);
        } 
    }
    
    @Override
    public void operationFailed(Exception e) {
        model.setSuccesfulImport(false);
        model.notifyObservers();
        String errorMsg = "An error in database import  occured.\nThe following error occured: "
            + e.getLocalizedMessage() + "\nThe import didn't take affect\n"
            + "Please note the the database might be in a currupt state and it may be needed to reset it";
        String errorTitle = "Database import failed";
        JOptionPane.showMessageDialog(getOwner(), errorMsg, errorTitle, JOptionPane.ERROR_MESSAGE);
    }
}
